package com.gem.netty.message;

import com.gem.entity.Game;
import com.gem.entity.Room;
import com.gem.entity.User;
import com.gem.enums.MessageColorType;
import com.gem.factory.card.CardBaseFactory;
import com.gem.factory.game.GameFactory;
import com.gem.factory.log.LogFactory;
import com.gem.factory.room.RoomFactory;
import com.gem.factory.user.UserFactory;
import com.gem.netty.entity.ClientContent;
import com.gem.netty.entity.CurrentUser;
import com.gem.netty.session.GroupSession;
import com.gem.netty.session.GroupSessionFactory;
import com.gem.utils.R;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Author: Xhy
 * CreateTime: 2022-09-24 17:19
 * 退出房间
 */
public class QuitRoomMessage implements Message{


    @Override
    public void handler(ClientContent content) {
        ChannelHandlerContext ctx = content.getCtx();

        String roomId = content.getRoomId();
        // 是否是最后一个人退出房间
        Room room = RoomFactory.get(roomId);
        String userId = content.getSendId();
        RoomFactory.removeUser(room,userId);
        ctx.writeAndFlush(new TextWebSocketFrame(R.ok().data("color", MessageColorType.SYSTEM_MESSAGE.type).message("退出房间成功").type(content.getType()).toString()));
        // 告诉房间内的玩家有人退出房间
        // 当前玩家退出该组
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        groupSession.removeMember(content.getRoomId(),content.getSendId());
        List<Channel> channels = groupSession.getMembersChannel(content.getRoomId());
        String userName = UserFactory.get(userId);
        groupSession.removeGroup(roomId);
        GameFactory.notifyUsers(channels,R.ok().data("color",MessageColorType.SYSTEM_MESSAGE.type).data("data",room.getRoomOwnerId()).message(userName+ "退出了房间").type(content.getType()),roomId);
    }




}
